const TemperatureModel = require('../models/temperatureModel')

const databridge = data => {
  console.log(data)
}

const deviceStatus = data => {
  console.log('设备连接状态：', data)
}

const temperature = async data => {
  let date = new Date() // 获取当前的日期和时间
  let hour = date.getHours() // 提取出小时
  let hourTimestamp = new Date(
    date.getFullYear(),
    date.getMonth(),
    date.getDate(),
    hour
  ).getTime()

  // 构建新的数据点
  const newPoint = {
    clientid: data.clientid,
    temperature: parseFloat(data.payload),
    time: parseInt(data.timestamp),
    qos: parseInt(data.qos),
    topic: data.topic
  }

  try {
    // 尝试找到文档并更新，如果不存在就创建
    await TemperatureModel.findOneAndUpdate(
      { clientid: data.clientid, hour: hourTimestamp }, // 查找条件
      {
        // push到points数组的操作，$setOnInsert用于设置仅在创建新文档时赋予clientId和hour
        $push: { points: newPoint },
        $setOnInsert: { clientid: data.clientid, hour: hourTimestamp }
      },
      {
        new: true, // 返回更新后的文档
        upsert: true // 如果不存在则插入新文档
      }
    )
  } catch (err) {
    console.error('Error updating or inserting temperature data', err)
    throw new HttpError(err.message, 400)
  }
}
module.exports = {
  databridge,
  deviceStatus,
  temperature
}
